package net.csdn.business.kanban.api.config;

import net.csdn.business.kanban.common.constant.CommonConstants;
import net.csdn.business.kanban.common.filter.CorsFilter;
import net.csdn.business.kanban.common.filter.ICorsConfig;
import net.csdn.business.kanban.common.filter.LogFilter;
import net.csdn.business.kanban.common.filter.RepeatableReadFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.List;

/**
 * @author likun
 * @date 2022/6/8 10:22
 */
@Configuration
public class FilterConfig {

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean logFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new LogFilter());
        registration.addUrlPatterns("/*");
        registration.setName("logFilter");
        registration.setOrder(-100);
        return registration;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @DependsOn("apiCorsFilter")
    public FilterRegistrationBean corsFilter(CorsFilter corsFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(corsFilter);
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(CommonConstants.INT_ZERO);
        return registration;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RepeatableReadFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableReadFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

    @Bean(name = "apiCorsFilter")
    @ConditionalOnMissingBean(CorsFilter.class)
    public CorsFilter initCorsFilter(ApiConfigData apiConfigData) {
        return new CorsFilter(new CorsFilterConfig(apiConfigData));
    }

    private static class CorsFilterConfig implements ICorsConfig {
        private final ApiConfigData apiConfigData;

        private CorsFilterConfig(ApiConfigData apiConfigData) {
            this.apiConfigData = apiConfigData;
        }

        @Override
        public String getAccessControlAllowHeaders() {
            return apiConfigData.getAccessControlAllowHeaders();
        }

        @Override
        public List<String> getAllowOrigins() {
            return apiConfigData.getAllowOrigins();
        }
    }

}